import { Component, ContentChild, ContentChildren, EventEmitter, Input, OnInit, Output, QueryList } from '@angular/core';

import { BaseDirective } from '../../../../core/models/base-directive.model';
import { DataGridOption } from '../shared/models/data-grid-option.model';
import { DataGridPageChangedEventArg } from '../shared/models/data-grid-page-changed-event-arg.model';
import { DataGridSelectionChangedEventArg } from '../shared/models/data-grid-selection-changed-event-arg.model';
import { DataGridConfig } from '../../../../core/config/data-grid.config';
import { DataGridColumnComponent } from './data-grid-column.component';
import { DataGridMasterDetailComponent } from './data-grid-master-detail.component';

declare const $: any;

@Component({
    selector: 'op-data-grid',
    templateUrl: './data-grid.component.html',
    styleUrls: ['./data-grid.component.scss']
})
export class DataGridComponent extends BaseDirective implements OnInit {
    @ContentChildren(DataGridColumnComponent) columns: QueryList<DataGridColumnComponent>;
    @ContentChild(DataGridMasterDetailComponent, {static: false}) masterDetail: DataGridMasterDetailComponent;
    @Output() pageChanged: EventEmitter<DataGridPageChangedEventArg> = new EventEmitter<DataGridPageChangedEventArg>();
    @Output() selectionChanged: EventEmitter<DataGridSelectionChangedEventArg> = new EventEmitter<DataGridSelectionChangedEventArg>();
    @Input() dataGridOption: DataGridOption;
    columnMinWidth: number;
    currentPage: number;
    totalPageCount: number = 0;
    selectedRowKeys: any[];

    constructor() {
        super();
    }

    ngOnInit(): void {
        super.ngOnInit();

        this.initializeProperties();
    }

    /**
     * Calculates the total page count based on the total rows count and page size.
     */
    calculateTotalPageCount(): number {
        return Math.ceil(this.dataGridOption.totalRowsCount / this.dataGridOption.pageSize);
    }

    /**
     * Emits the pageChange event when page changes.
     * @param e: The page change event sent by the paginator component.
     */
    onPageChanged(e: any): void {
        this.dataGridOption.pageSize = e.rows;
        this.currentPage = e.page + 1;
        this.totalPageCount = e.pageCount;

        this.pageChanged.emit({
            pageStartIndex: e.first,
            pageEndIndex: e.first + e.rows,
            pageSize: this.dataGridOption.pageSize
        });
    }

    /**
     * Emits the selectionChange event when grid row selction changes.
     * @param e: The selection change event sent by the paginator component.
     */
    onSelectionChanged(e: any): void {
        // This is for clear selection button.
        this.selectedRowKeys = e.selectedRowKeys;

        this.selectionChanged.emit({
            selectedRowKeys: e.selectedRowKeys,
            selectedRowsData: e.selectedRowsData
        });
    }

    /**
     * Triggered when the data grid content is ready. The right place to apply some extra styles for data grid.
     * @param e: The content ready event sent by the data grid component.
     */
    onContentReady(e: any): void {
        // By now this is for fixing the issue of boostrap dropdown being blocked in the DataGrid cell.

        // this.columns.filter(p => p.allowOverflow).forEach(p => {            
        //     $(`[aria-label^="Column ${p.title}"]`).css('overflow', 'visible');
        // });

        // $('.dx-scrollable-container').css('overflow', 'auto');
        // $('.dx-datagrid-rowsview').css('overflow', 'visible');
    }

    /**
     * Initializes the class properties if necessary.
     */
    protected initializeProperties(): void {
        this.dataGridOption.dataSource = this.dataGridOption.dataSource || [];
        this.dataGridOption.totalRowsCount = this.dataGridOption.totalRowsCount || 0;
        this.dataGridOption.keyName = this.dataGridOption.keyName || DataGridConfig.keyName;
        this.dataGridOption.pageSize = this.dataGridOption.pageSize || DataGridConfig.pageSize;
        this.dataGridOption.pageSizeOptions = this.dataGridOption.pageSizeOptions || DataGridConfig.pageSizeOptions;
        this.dataGridOption.pageLinkSize = this.dataGridOption.pageLinkSize || DataGridConfig.pageLinkSize;
        this.columnMinWidth = DataGridConfig.columnMinWidth;
        this.currentPage = 1;
        this.selectedRowKeys = [];
    }
}